/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2023-11-15 09:45:31
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-05 17:42:19
 * @FilePath: \cxl-driving-training\src\store\router.store.ts
 */
import router from '@/router'
import { defineStore } from 'pinia'
import { storage } from './sessionStorage'
import { LocationQueryRaw, RouteParamsRaw } from 'vue-router'
import { userMenuTree } from '@/apis/system/menu'
import Layout from '@/layout/Index.vue'

//vite // 首先把你需要动态路由的组件地址全部获取
const modules = import.meta.glob('../views/**/*Index.vue')

/**
 * 定义顶部菜单路由信息接口
 */
export interface HeaderRouterInterface {
    path: string
    title: string
    activePath?: string
    hidden?: boolean
    params?: object
    query?: object
}
/**
 * 定义state中所有信息类型
 */
export interface routers {
    headerRouters: Array<HeaderRouterInterface>
    selectIndex: number
    defaultActivePath: string
    permission: string[]
    menu: any[]
    routeArray: any[]
    tree: any[]
}

interface metaInterface {
    title: string
    hidden?: boolean
    activePath?: string
    icon?: string
}

// 左侧导航菜单接口
interface menuRouterInterface {
    path: string
    title?: string
    icon?: string
    name?: string
    component?: any
    redirect?: string
    meta?: metaInterface
    children?: menuRouterInterface[]
}

export const routerStore = defineStore('routerStore', {
    state: (): routers => {
        return {
            headerRouters: [{ path: '/index', title: '首页' }],
            selectIndex: 0,
            defaultActivePath: '/index',
            permission: [],
            menu: [],
            routeArray: [],
            tree: []
        }
    },
    actions: {
        //重置数据
        resetData() {
            this.permission.length = 0
            this.menu.length = 0
            this.routeArray.length = 0
            this.tree.length = 0

            //删除多余的导航
            if (this.headerRouters.length > 1) {
                this.headerRouters.splice(1, this.headerRouters.length - 1)
            }
        },
        /**
         * 获取路由
         * @returns
         */
        async getRoute() {
            return new Promise((resolve, reject) => {
                userMenuTree().then((res: any) => {
                    if (Number(res.data.code) === 200) {
                        this.routeArray.length = 0
                        const list = setTree(res.data.result)
                        this.routeArray.push(...list)
                        this.permission.length = 0
                        this.permission.push('*', ...setPermission(res.data.result))
                        resolve(list)
                    }
                })
            })
        },
        /**
         * 设置顶部路由菜单
         * @param target
         */
        setHeaderRouter(target: HeaderRouterInterface) {
            let has = false

            //判断传递 target 的路由路径是否存在 this.headerRouters 中
            this.headerRouters.forEach((item: HeaderRouterInterface, index: number) => {
                if (item.path == target.path) {
                    has = true
                    item.title = target.title
                    item.params = target.params
                    item.path = target.path
                    item.query = target.query
                    item.activePath = target.activePath
                    item.hidden = target.hidden
                    this.selectIndex = index
                }

                if (item.path === '/system/menu/edit') {
                    if (JSON.stringify(target.query) == '{}') {
                        const query = JSON.parse('menuParams')[0]
                        item.title = query.type == 'create' ? '新增菜单' : '菜单编辑'
                    } else {
                        const query = JSON.parse(JSON.stringify(target.query))
                        item.title = query.type == 'create' ? '新增菜单' : '菜单编辑'
                    }
                } else if (item.path === '/system/notice/edit') {
                    // console.log('公告消息', JSON.stringify(target.query))
                    if (JSON.stringify(target.query) == '{}') {
                        // console.log(item.title, target.title)
                    } else {
                        const query = JSON.parse(JSON.stringify(target.query))
                        item.title = query.type == 'create' ? '新增消息' : '消息编辑'
                    }
                }
            })

            //不存在
            if (!has) {
                //设置顶部菜单当前选中的下标
                this.selectIndex = this.headerRouters.length

                //添加到 this.headerRouters
                this.headerRouters.push(target)
            }

            //并设置左侧默认路由地址
            this.defaultActivePath = target.hidden ? (target.activePath as string) : target.path
        },
        removeHeaderRoute(index: number): void {
            if (index === this.selectIndex) {
                //删除的下标等于选中的下标

                //设置选中下标
                this.selectIndex = index - 1

                //设置选中路径
                this.defaultActivePath = this.headerRouters[this.selectIndex].path

                //从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)

                //页面进行跳转
                this.routerPush(this.selectIndex === 0 ? undefined : this.selectIndex)
            } else if (index < this.selectIndex) {
                //删除的下标小于选中的下标，设置选中的下标等于删除的下标

                this.selectIndex = this.selectIndex - 1

                //从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)
            } else {
                //删除的下标大于选中的下标 直接从 this.headerRouters 中删除
                this.headerRouters.splice(index, 1)
            }

            //遍历当前数组，判断是否存在
            //判断编辑菜单页面是否存在
            let hasMenuEditExist = false
            this.headerRouters.forEach((item: HeaderRouterInterface, index: number) => {
                if (item.path === '/system/menu/edit') {
                    hasMenuEditExist = true
                }
            })
            //不存在，删除本地菜单数据
            if (!hasMenuEditExist) {
                storage.remove('menuParams')
            }
        },
        /**
         * 顶部导航右键操作
         * @param type
         * @param index
         */
        contextOperate(type: string, index: number) {
            // console.log(type, 'index', index, 'selectIndex', this.selectIndex)
            if (type === 'all') {
                //关闭全部页面，跳转到首页
                this.routerPush()

                this.headerRouters.splice(1, this.headerRouters.length - 1)
            } else if (type === 'current') {
                //关闭当前页面
                this.removeHeaderRoute(index)
            } else if (type === 'right') {
                //关闭右侧菜单页面
                this.headerRouters.splice(index + 1, this.headerRouters.length - index - 1)
                if (index < this.selectIndex) {
                    this.selectIndex = index

                    this.routerPush(this.selectIndex ? this.selectIndex : undefined)
                }
            } else if (type === 'left') {
                //关闭左侧菜单页面
                this.headerRouters.splice(1, index - 1)
                this.selectIndex = this.selectIndex - (index - 1)

                this.routerPush(index <= this.selectIndex ? this.selectIndex : undefined)

                console.log(this.selectIndex)
            } else if (type === 'other') {
                //关闭其它页面
                if (index === 0) {
                    this.headerRouters.splice(1, this.headerRouters.length - 1)
                    this.selectIndex = 0
                } else {
                    this.headerRouters.splice(index + 1, this.headerRouters.length - index - 1)
                    this.headerRouters.splice(1, index - 1)
                    this.selectIndex = 1
                }

                this.routerPush(this.selectIndex === 0 ? undefined : this.selectIndex)
            } else if (type === 'reload') {
                //刷新当前页面
                router.go(0)
            }
        },
        //设置页面跳转
        routerPush(index?: number) {
            if (index !== undefined) {
                router.push({
                    path: this.headerRouters[index].path,
                    query: (this.headerRouters[index].query as LocationQueryRaw) ?? undefined,
                    params: (this.headerRouters[index].params as RouteParamsRaw) ?? undefined
                })
            } else {
                router.push({
                    path: '/index',
                    query: {},
                    params: {}
                })
            }
        }
    }
})

function setTree(list: any[] = []) {
    const arr: menuRouterInterface[] = []

    list.forEach((item: any) => {
        if (item.type === 0 && item.disable === 0) {
            //菜单
            const obj: menuRouterInterface = {
                path: item.routePath,
                name: item.componentName,
                children: [],
                meta: {
                    title: item.name,
                    icon: item.icon,
                    activePath: item.routePath,
                    hidden: true
                }
            }
            if (!item.component && item.subPermissions.length) {
                obj.component = Layout
                obj.children?.push(...setTree(item.subPermissions))
            } else {
                obj.component = modules[`../views${item.component}/Index.vue`]
            }
            arr.push(obj)
        }
    })
    return arr
}

// setPermission()
function setPermission(list: any[] = []) {
    const arr: string[] = []

    list.forEach((item: any) => {
        if (item.disable === 0) {
            if (item.subPermissions.length) {
                arr.push(...setPermission(item.subPermissions))
            }
            if (item.type !== 0) {
                //按钮 接口
                arr.push(item.permsUrl)
            }
        }
    })
    return arr
}
